import {
    Action
} from 'redux';

import * as types from './../types/browse';
import * as commonTypes from './../types/common';

interface _Action extends Action {
    data: any
}

interface State {
    list: []
}

const initState = {} as State;

export default (
    state = initState,
    action: _Action
) => {
    const {
        type,
        data
    } = action;

    switch (type) {
        case types.getBrowseList: {
            const {
                isPush,
                queryList
            } = data;

            const {
                list = []
            } = state;

            state.list = (
                isPush ? [...list, ...queryList] : queryList
            )

            return {
                ...state
            }
        }

        case commonTypes.postLikeUser: {
            const {
                userId
            } = data;

            const {
                list = []
            } = state;

            const index = list.findIndex((item: any) => {
                return item.userId === userId;
            })

            if (index > -1) {
                (list[index] as any).isLiked = 1;

                return {
                    ...state,
                    list: [...list]
                }
            }
        }

        case commonTypes.postUnlikeUser:{
            const {
                userId
            } = data;

            const {
                list = []
            } = state;

            const index = list.findIndex((item: any) => {
                return item.userId === userId;
            })

            if (index > -1) {
                (list[index] as any).isLiked = -1;

                return {
                    ...state,
                    list: [...list]
                }
            }
        }

        case commonTypes.resetLikeUser: {
            const {
                userId
            } = data;

            const {
                list = []
            } = state;

            const index = list.findIndex((item: any) => {
                return item.userId === userId;
            })

            if (index > -1) {
                (list[index] as any).isLiked = 0;

                return {
                    ...state,
                    list: [...list]
                }
            }
        }

        case commonTypes.blockUser : {
            const {
                userId
            } = data;

            const {
                list = []
            } = state;

            const index = list.findIndex((item: any) => {
                return item.userId === userId;
            })

            if (index > -1) {
                list.splice(index,1)
                return {
                    ...state,
                    list: [...list]
                }
            }
        }
    }

    return state;
}